/**
 * Created by Fly on 2016/9/19.
 */
var express = require('express');
var router = express.Router();
var forsterDAO=require('../dao/forsterDao');
var formidable=require('formidable');
var fs=require('fs');

router.post('/addfoster',function(req,res){
    forsterDAO.add(req,res,function(result){
        if(result.affectedRows==1){
            res.json({res:"1"});
        }else{
            res.json({res:"0"});
        }
    });
});
router.post('/apply',function(req,res){
    var form=new formidable.IncomingForm();
    var a=new Array(2);
    form.uploadDir="../public/upload/";
    form.parse(req,function(err,fields,files){
        if(err){
            res.locals.error=err;
            return;
        }
            var extName='';//后缀名
            switch(files.file1.type){
                case 'image/jpeg':
                    extName='jpeg';
                    break;
                case 'image/jpg':
                    extName='jpg';
                    break;
                case 'image/png':
                    extName='png';
                    break;
                case 'image/x-png':
                    extName='png';
                    break;
            }
            if(extName.length==0){
                res.send('只支持png和jpg格式图片');
                return;
            }else{
                form.uploadDir="../public/images/";
                form.keepExtensions=true;
                form.maxFieldsSize=2*1024;
                a[0]=Math.random()+'.'+extName;
                var newPath=form.uploadDir+a[0];
                fs.renameSync(files.file1.path,newPath);
                console.log('add img ---end');
            }
            var extName='';//后缀名
            switch(files.file2.type){
                case 'image/jpeg':
                    extName='jpeg';
                    break;
                case 'image/jpg':
                    extName='jpg';
                    break;
                case 'image/png':
                    extName='png';
                    break;
                case 'image/x-png':
                    extName='png';
                    break;
        }
        if(extName.length==0){
            res.send('只支持png和jpg格式图片');
            return;
        }else{
            form.uploadDir="../public/images/";
            form.keepExtensions=true;
            form.maxFieldsSize=2*1024;
            a[1]=Math.random()+'.'+extName;
            var newPath=form.uploadDir+a[1];
            fs.renameSync(files.file2.path,newPath);
            console.log('add img ---end');
        }
        console.log("得到的结果"+JSON.stringify(fields));
        console.log('第一个文件'+a[0]+'第二个文件'+a[1]);
        forsterDAO.apply(req,fields,a,function(result){
            if(result.affectedRows==1){
                res.json({res:"1"});
            }else{
                res.json({res:"0"});
            }
        });
    });

});

module.exports = router;